import XGHandler from "../mysql/shopping.js"
export default class StepNumber{
    elem;
    left;
    right;
    input;
    step=1;
    ids;
    id;
    constructor(){
         this.elem=document.createElement("div");
         this.elem.className="step-number"
         this.left=document.createElement("div");
         this.left.innerHTML="-"
        //  this.left.setAttribute("disabled","")
         this.right=document.createElement("div");
         this.left.className=this.right.className="bn";
         this.right.innerHTML="+"
         this.input=document.createElement("input");
         this.input.type="text";
         
         this.input.className="input-txt";
         this.elem.appendChild(this.left)
         this.elem.appendChild(this.input)
         this.elem.appendChild(this.right);
         this.left.addEventListener("click",e=>this.clickHandler(e));
         this.right.addEventListener("click",e=>this.clickHandler(e));
         this.input.addEventListener("input",e=>this.inputHandler(e));
         this.setStep(this.step);
    }
    appendTo(parent){
        if(typeof parent==="string") parent=document.querySelector(parent);
        if(parent) parent.appendChild(this.elem);
    }
    inputHandler(e){
        this.input.value=this.input.value.replace(/\D/g,"");
        if(this.ids) return;
        this.ids=setTimeout(()=>{
            clearTimeout(this.ids);
            this.ids=undefined;
            this.setStep(this.input.value);
            this.dispatch();
        },500);
    }
    clickHandler(e){
        if(e.currentTarget===this.left){
            this.setStep(this.step-1);
        }else if(e.currentTarget===this.right){
            this.setStep(this.step+1);
        }
        this.dispatch();
      XGHandler.XGHandler(this.step,this.pid)
    }
    dispatch(){
        var evt=new Event("change_step_event");
        evt.step=this.step;
        evt.id=this.id;
        document.dispatchEvent(evt);
    }
    setStep(_step){
        _step=Number(_step);
        this.left.removeAttribute("disabled")
        this.right.removeAttribute("disabled")
        if(_step<=1){
            _step=1;
            this.left.setAttribute("disabled","")
        }
        if(_step>=99){
             _step=99;
             this.right.setAttribute("disabled","")
        }
        this.step=_step;
        this.input.value=this.step;
        
    }
}